import {ref, computed} from "vue";
import {defineStore} from "pinia";
import {userLoginApi, getUserInfoApi, getUserMenuApi, getUserPermissionApi} from "@/api/account";


export const useUserStore = defineStore("user", () => {
    const userToken = ref<{ access: string; refresh: string; }>({
        access: "",
        refresh: ""
    });
    const userInfo = ref();
    const userMenus = ref<any[]>();
    const userPermissions = ref();
    const isLogin = computed(() => !!userToken.value?.access);


    /**
     * 保存验证信息
     * @param username 用户名
     * @param password 密码
     */
    async function getUserToken(username: string, password: string) {
        const response = await userLoginApi({
            username: username,
            password: password
        });
        userToken.value = response.data;
    }


    /**
     * 保存用户信息
     */
    async function getUserInfo() {
        if (isLogin.value) {
            const response = await getUserInfoApi();
            userInfo.value = response.data;
        }
    }


    /**
     * 保存用户菜单
     */
    async function getUserMenus() {
        if (isLogin.value) {
            const response = await getUserMenuApi();
            userMenus.value = response.data;
        }
    }


    /**
     * 获取用户权限
     */
    async function getUserPermission() {
        if (isLogin.value) {
            const response = await getUserPermissionApi();
            userPermissions.value = response.data;
        }
    }


    /**
     * 清除用户数据
     */
    function clearUserAuthorization() {
        userToken.value = {
            access: "",
            refresh: ""
        };
        userInfo.value = undefined;
        userMenus.value = undefined;
        userPermissions.value = undefined;
    }


    return {
        userToken,
        userInfo,
        userMenus,
        userPermissions,
        isLogin,
        getUserToken,
        getUserInfo,
        getUserMenus,
        getUserPermission,
        clearUserAuthorization
    }
}, {
    persist: true
})
